#!/usr/bin/env python

import os
from liwe.module import LiweModule

class System ( LiweModule ):
	def __init__ ( self, liwe ):
		super ( System, self ).__init__ ( liwe, "system" )

	def list_modules ( self ):
		res = []
		dirs = os.listdir ( "modules" )

		for d in dirs:
			if os.path.isdir ( os.path.join ( "modules", d ) ) and d != "CVS":
				res.append ( d )

		return res

	def list_all_modules ( self ):
		mods = self.list_modules ()
		
		res = {}
		for m in mods:
			txt = self.module_list_perms ( m ).get ( '_txt', '' )
			if txt: res [ m ] = eval ( txt )

		return res

	def module_list_config ( self, module_name ):
		return self.liwe.invoke ( module_name + ".__init__.list_config" )

	def module_get_all_configs ( self, module_names = None ):
		vals = {} 

		if module_names: 
			mod_lst = module_names.split ( '|' )
		else: 
			mod_lst = self.list_modules ()

		for mod in mod_lst:
			confs = self.module_list_config ( mod )
			if '_txt' not in confs: continue

			vals [ mod ] = eval ( confs  [ '_txt' ] )

		return vals 

	def module_config_save ( self, kwargs ):
		mod_name = kwargs [ 'module_name' ]
		del kwargs [ 'module_name' ]

		self._config_save ( mod_name, 0, kwargs )

	def module_list_perms ( self, module_name ):
		return self.liwe.invoke ( module_name + ".__init__.list_perms", None )

	def module_get_all_perms ( self, module_names, uid, perms_type = 'user' ):
		vals = {} 
		if module_names : 
			mod_lst = module_names.split ( '|' )
		else: 
			mod_lst = self.list_all_modules ()

		for mod in mod_lst:
			perms = self.module_get_perms ( mod, uid, perms_type )
			vals [ mod ] = perms 
		return vals 

	def module_get_perms ( self, module_name, uid, perms_type = 'user' ):
		conds = []
		conds.append ( " module_name = '%s' " % module_name )

		if perms_type == 'user':
			table = 'user_perm'
			conds.append ( "uid = '%s'" % uid )

		if perms_type == 'group':
			table = 'user_group_perm'
			conds.append ( "gid = '%s'" % uid )

		vals = self.dbm.single_row ( table , "perms", ' AND '.join ( conds ) )
		if not vals:
			return []

		return vals [ 'perms' ].split ( ":" )

	def module_set_perms ( self, module_name, uid, perms, perms_type = 'user' ):
		"""
		perms: string of perms key separated by ":"
		"""
		conds = []
		conds.append ( "module_name = '%s'" % module_name )
		dct = { "perms" : perms, "module_name" : module_name }

		if perms_type == 'user':
			table = "user_perm"
			conds.append (  "uid = '%s'" % uid )
			dct [ 'uid' ] = uid

		if perms_type == 'group':
			table = "user_group_perm"
			conds.append (  "gid = '%s'" % uid )
			dct [ 'gid' ] = uid

		#self.dbm.debug = sys.stderr.write
		self.dbm.delete ( table, ' AND '.join ( conds ) )
		self.dbm.insert ( table, dct )
		#self.dbm.debug = None

	def load_page ( self, page_name, block_name = None ):
		html = self.liwe.layman.load_page ( page_name, block_name )

		return html

	def modules_check ( self ):
		mods = self.list_modules ()
		mods.sort ()
		res = []
		for m in mods:
			info = self.liwe.invoke ( m + ".__init__.get_module_info" ) 
			
			if info [ 'err_code' ] != 0: continue
			if not info.get ( 'dir_name' ): continue

			#sys.stderr.write ( "\n\n**** MODULE: %s - %s\n" % ( m, info ) )

			cls = __import__ ( "modules.%(dir_name)s.%(file_name)s" % info )
			cls = getattr ( cls, info [ 'dir_name' ] )
			cls = getattr ( cls, info [ 'file_name' ] )
			instance = getattr ( cls, info [ "class_name" ] ) ( self.liwe )
			m = self.liwe.invoke ( m + ".__init__.get_cfg_data" )
			res += [ { "module" : info [ 'class_name' ], "checks" : instance.check ( m ) } ]

		return res

	def modules_sitemap ( self ):
		mods = self.list_modules ()
		mods.sort ()
		res = []
		for m in mods:
			data = self.liwe.invoke ( m + ".ajax.sitemap" )
			if data [ 'err_code' ]: continue

			del data [ 'err_code' ]
			del data [ 'err_descr' ]

			if data:
				res.append ( { "module" : m, "data" : data } )

		return res

	def session_clean ( self ):
		pass

	def tables_settings ( self ):
		res = self.dbm.all_rows ( 'information_schema.tables', [ 'table_name', 'table_type', 'engine', 'table_collation' ], conds = "table_schema = database()" )
		return res

	def _config_save ( self, module_name, user_id, config ):
		data = self.dbm.pickle ( config )
		self.dbm.delete ( "liwe_config", "module_name = '%s' AND uid = '%s'" % ( module_name, user_id ) )
		self.dbm.insert ( "liwe_config", { "module_name" : module_name, "uid" : user_id, "data" : data } )

